package tjs.study.notes.dotest.jdk;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Nicky.Tang on 2022/11/16 上午10:43
 *
 * @since 02.12.10
 */
public class 正态分布 {
    /**
     * 68.2% 的数据分布在 平均值-1个标准差 <= x <= 平均值+1个标准差
     * 95.4% 的数据分布在 平均值-2个标准差 <= x <= 平均值+2个标准差
     *
     * @param args
     */
    public static void main(String[] args) {
        List<Long> clockDifArray = Arrays.asList(1L, 2L, 9L, 10L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 100L, 102L);
        //DescriptiveStatistics stats = new DescriptiveStatistics();
        //for (Long dif : clockDifArray) {
        //    stats.addValue(dif);  //这个方法有性能问题
        //}
        DescriptiveStatistics stats = new DescriptiveStatistics(
                clockDifArray.stream().filter(val -> val != null).mapToDouble(item->item).toArray());
        double deviation = stats.getStandardDeviation();
        double avg = stats.getSum() / stats.getN();
        double max = avg + deviation * 2;
        double min = avg - deviation * 2;
        List<Long> clockRemove = clockDifArray.stream().filter(item -> item >= min && item <= max).collect(Collectors.toList());
        // 去除毛刺
        double differenceD = CollectionUtils.isEmpty(clockRemove) ? avg : clockRemove.stream().mapToLong(item -> item).average().getAsDouble();
        System.out.println("标准差：" + deviation + "; max：" + max + "; min：" + min);
        System.out.println("毛刺数组：" + JSONObject.toJSONString(clockDifArray.stream().filter(item -> !(item >= min && item <= max)).collect(Collectors.toList()))
                + "\n去除毛刺后的平均值：" + differenceD);
    }
}
